package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.datas.SubmitOrderNewRequest
import org.lzy.shop.response.ConifimOrderResponse
import org.lzy.shop.response.SubmitOrderSuccessResponse
import org.lzy.shop.util.ToastUtil
import org.lzy.shop.viewmodel.repository.SubmitOrderRepository
import org.lzy.shop.viewmodel.repository.lmpl.SubmitOrderRepositoryImpl

/**
 * 提交订单的VM层
 */
class SubmitOrderModel() : BaseViewModel(){

    private val submitOrderRepository: SubmitOrderRepository = SubmitOrderRepositoryImpl()


    val submitOrderAddData = MutableLiveData<SubmitOrderSuccessResponse?>()
    val getConfirmOrderData = MutableLiveData<ConifimOrderResponse?>()

    /**
     * 确认订单信息
     */
    fun confirmOrder(): LiveData<ConifimOrderResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = submitOrderRepository.confirmOrder()
                if (response != null) {
                    getConfirmOrderData.value = response
                } else {
                    errorMessage.value = "获取确认订单信息失败"
                }
            } catch (e: Exception) {
                errorMessage.value = e.message ?: "获取确认订单信息异常"
            }
        }

        return getConfirmOrderData
    }

    /**
     * 提交订单
     */
    fun createOrder(request: SubmitOrderNewRequest): LiveData<SubmitOrderSuccessResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = withTimeout(24000) {
                    submitOrderRepository.createOrder(request)
                }
                if (response != null) {
                    submitOrderAddData.value = response
                } else {
                    val errorMsg = "提交订单失败"
                    errorMessage.value = errorMsg
                    ToastUtil.showError(errorMsg)
                }
            } catch (e: Exception) {
                val errorMsg = e.message ?: "提交订单异常"
                errorMessage.value = errorMsg
                ToastUtil.showError(errorMsg)
            }
        }

        return submitOrderAddData
    }
}